from rest_framework import viewsets
from rest_framework.permissions import SAFE_METHODS

from .models import Record
from .serializers import GetRecordSuperSerializer, PostRecordSuperSerializer
from rest_framework.response import Response

from rest_framework import permissions


class RecordViewSet(viewsets.ModelViewSet):

    queryset = Record.objects.all()
    serializer_class = GetRecordSuperSerializer
    permission_classes = [permissions.IsAdminUser]
    # filter_backends = [UserAllowPermissionFilterBackend]

    def get_serializer_class(self):
        if self.request.method in SAFE_METHODS:
            if self.request.user.is_superuser:
                return GetRecordSuperSerializer
        else:
            return PostRecordSuperSerializer


class RecordAdd(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAdminUser]
    serializer_class = GetRecordSuperSerializer
    queryset = Record.objects.all()

    def create(self, request, *args, **kwargs):
        data = request.data
        serializer = PostRecordSuperSerializer(data=data)
        try:
            serializer.is_valid(raise_exception=True)
            serializer.save()
            return Response({
                "flag": True,
                "code": 0,
                "errorMsg": "操作成功"
            }, status=200)
        except Exception as e:
            return Response({
                "flag": False,
                "code": 400,
                "errorMsg": e.__str__()
            }, status=208)

